package com.smallcc.service.impl;

import com.smallcc.exception.SellException;
import com.smallcc.service.RedisLock;
import com.smallcc.service.SeckillService;
import com.smallcc.util.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 晓风过境
 * @TODO
 * @date 2018/4/4 20:34
 * @day 04
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@Service
public class SecKillServiceImpl implements SeckillService {
    @Autowired
    private RedisLock lock;
    private static final int TimeOut=10*1000;//超时时间是10秒

    static Map<String,Integer> products;
    static Map<String,Integer> stock;
    static Map<String,String> orders;
    static
    {
        /**
         * 模拟多张表
         */
        products=new HashMap<>();
        stock=new HashMap<>();
        orders=new HashMap<>();
        products.put("123456",1000);
        stock.put("123456",1000);

    }

    private String queryMap(String productId){
        return "国庆活动，限量冷吃兔"+products.get(productId)+"还剩"+stock.get(productId)+"份、、、"+orders.size()+"人";
    }

    public String querySeckillProductInfo(String productId) {
        return this.queryMap(productId);
    }

    public void orderProductMockDiffUser(String productId) {
        //加锁
        Long time=System.currentTimeMillis()+TimeOut;
        if(!lock.lock(productId,String.valueOf(time))){
            throw new SellException(101,"人太多了，换个姿势在试试~~");
        }
        int stockNum=stock.get(productId);
        if(stockNum==0){
            throw  new SellException(100,"活动结束");
        }else {

            orders.put(KeyUtil.genUniqueKey(),productId);
            stockNum=stockNum-1;
            try{
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            stock.put(productId,stockNum);
        }
        //解锁
        lock.unlock(productId,String.valueOf(time));
    }
}
